'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/hooks/use-auth'
import { useParameterPermissions } from '@/hooks/use-parameter-permissions'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'

export default function TestDesignPermissionsPage() {
  const { user, permissions, hasDataSourceAccess } = useAuth('table_c2')
  const {
    fields,
    loading,
    error,
    getFieldsByDataSource
  } = useParameterPermissions('table_c2', 1)

  const [testResults, setTestResults] = useState<any[]>([])

  useEffect(() => {
    if (fields.length > 0 && user && permissions) {
      const results = []
      
      // 测试数据来源权限
      const dataSources = ['E', 'P', 'C', 'R']
      dataSources.forEach(source => {
        const hasAccess = hasDataSourceAccess(source)
        const sourceFields = getFieldsByDataSource(source)
        
        results.push({
          type: 'dataSource',
          source,
          hasAccess,
          fieldCount: sourceFields.length,
          editableCount: sourceFields.filter(f => f.canEdit).length
        })
      })
      
      // 测试具体字段权限
      fields.forEach(field => {
        if (field.data_source === 'E') {
          results.push({
            type: 'field',
            fieldName: field.field_name,
            dataSource: field.data_source,
            canEdit: field.canEdit,
            isVisible: field.isVisible
          })
        }
      })
      
      setTestResults(results)
    }
  }, [fields, user, permissions, hasDataSourceAccess, getFieldsByDataSource])

  if (loading) {
    return <div className="p-8">加载中...</div>
  }

  if (error) {
    return <div className="p-8 text-red-600">错误: {error}</div>
  }

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">设计权限测试</h1>
      
      {/* 用户信息 */}
      <Card>
        <CardHeader>
          <CardTitle>当前用户信息</CardTitle>
        </CardHeader>
        <CardContent>
          {user ? (
            <div className="space-y-2">
              <div><strong>用户名:</strong> {user.username}</div>
              <div><strong>姓名:</strong> {user.full_name}</div>
              <div><strong>角色:</strong> {user.role_name} ({user.role_code})</div>
            </div>
          ) : (
            <div className="text-red-600">未登录</div>
          )}
        </CardContent>
      </Card>

      {/* 权限信息 */}
      <Card>
        <CardHeader>
          <CardTitle>权限配置</CardTitle>
        </CardHeader>
        <CardContent>
          {permissions ? (
            <div className="space-y-2">
              <div><strong>管理员权限:</strong> {permissions.canEditAll ? '是' : '否'}</div>
              <div><strong>数据来源权限:</strong> {permissions.dataSourceAccess.join(', ')}</div>
              <div><strong>可编辑字段数:</strong> {permissions.editableFields?.length || 0}</div>
            </div>
          ) : (
            <div className="text-red-600">无权限信息</div>
          )}
        </CardContent>
      </Card>

      {/* 测试结果 */}
      <Card>
        <CardHeader>
          <CardTitle>权限测试结果</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* 数据来源权限测试 */}
            <div>
              <h4 className="font-medium mb-2">数据来源权限测试</h4>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {testResults.filter(r => r.type === 'dataSource').map(result => (
                  <div key={result.source} className="border rounded p-3">
                    <div className="flex items-center justify-between mb-2">
                      <Badge className={result.hasAccess ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                        {result.source}
                      </Badge>
                      <span className="text-xs">{result.hasAccess ? '有权限' : '无权限'}</span>
                    </div>
                    <div className="text-sm text-gray-600">
                      <div>字段数: {result.fieldCount}</div>
                      <div>可编辑: {result.editableCount}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* E字段详细测试 */}
            <div>
              <h4 className="font-medium mb-2">E (设计) 字段权限详情</h4>
              <div className="space-y-2">
                {testResults.filter(r => r.type === 'field').map((result, index) => (
                  <div key={index} className="flex items-center justify-between p-2 border rounded">
                    <span className="font-medium">{result.fieldName}</span>
                    <div className="flex items-center space-x-2">
                      <Badge variant={result.isVisible ? 'default' : 'secondary'}>
                        {result.isVisible ? '可见' : '隐藏'}
                      </Badge>
                      <Badge variant={result.canEdit ? 'default' : 'destructive'}>
                        {result.canEdit ? '可编辑' : '只读'}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 调试信息 */}
      <Card>
        <CardHeader>
          <CardTitle>调试信息</CardTitle>
        </CardHeader>
        <CardContent>
          <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto max-h-96">
            {JSON.stringify({
              user,
              permissions,
              fieldsCount: fields.length,
              testResults
            }, null, 2)}
          </pre>
        </CardContent>
      </Card>
    </div>
  )
}
